package com.example.smartmedicalsystem.service;

import com.example.smartmedicalsystem.entity.*;
import com.example.smartmedicalsystem.repository.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class AppointmentService {
    private final AppointmentRepository appointmentRepository;
    private final DoctorRepository doctorRepository;
    private final ScheduleRepository scheduleRepository;
    private final MedicalRecordRepository medicalRecordRepository;
    private final MessageRepository messageRepository; // 新增依赖
    private final MedicineRepository medicineRepository; // 新增药品依赖

    @Transactional
    public boolean bookAppointment(Long patientId, Long doctorId, Long scheduleId) {
        // 获取完整实体对象
        Doctor doctor = doctorRepository.findById(doctorId)
                .orElseThrow(() -> new RuntimeException("医生不存在"));
        Schedule schedule = scheduleRepository.findById(scheduleId)
                .orElseThrow(() -> new RuntimeException("排班不存在"));

        Appointment appointment = new Appointment();
        User patient = new User();
        patient.setId(patientId);
        appointment.setPatient(patient);
        appointment.setDoctor(doctor);
        appointment.setSchedule(schedule);
        appointment.setStatus(Appointment.Status.PENDING);
        appointmentRepository.save(appointment);

        // 构建消息内容
        Message msg = new Message();
        msg.setContent(String.format("新预约：患者ID %d 于 %s %s",
                patientId,
                schedule.getDate(),
                schedule.getTimeSlot()));
        msg.setReceiver(doctor.getUser());
        msg.setTimestamp(LocalDateTime.now());
        messageRepository.save(msg);

        return true;
    }

    @Transactional
    public MedicalRecord completeAppointment(Long appointmentId,
                                             String diagnosis,
                                             String prescription,
                                             List<MedicineQuantity> medicines) { // 新增药品参数
        Appointment appointment = appointmentRepository.findById(appointmentId)
                .orElseThrow(() -> new RuntimeException("预约不存在"));

        if (appointment.getStatus() != Appointment.Status.PENDING) {
            throw new RuntimeException("该预约已处理");
        }

        // 检查并更新药品库存
        medicines.forEach(mq -> {
            Medicine medicine = medicineRepository.findById(mq.medicineId())
                    .orElseThrow(() -> new RuntimeException("药品不存在: " + mq.medicineId()));
            if (medicine.getStock() < mq.quantity()) {
                throw new RuntimeException(medicine.getName() + " 库存不足");
            }
            medicine.setStock(medicine.getStock() - mq.quantity());
            medicineRepository.save(medicine);
        });

        // 更新预约状态
        appointment.setStatus(Appointment.Status.COMPLETED);
        appointmentRepository.save(appointment);

        // 创建病历记录
        MedicalRecord record = new MedicalRecord();
        record.setAppointment(appointment);
        record.setDiagnosis(diagnosis);
        record.setPrescription(prescription);

        // 保存药品信息（需要实体类支持）
        medicines.forEach(mq -> {
            Medicine medicine = medicineRepository.findById(mq.medicineId()).get();
            record.addMedicine(medicine, mq.quantity());
        });
        Message patientMsg = new Message();
        patientMsg.setContent("诊断已完成！");
        patientMsg.setReceiver(appointment.getPatient());
// 添加直接查看链接
        patientMsg.setContent("诊断结果已生成，<a href='/medical_record.html?appointmentId="
                + appointmentId + "'>点击查看详情</a>");
        messageRepository.save(patientMsg);
        return medicalRecordRepository.save(record);

    }

    public List<Appointment> getPendingAppointmentsByDoctor(Long doctorId) {
        Doctor doctor = doctorRepository.findById(doctorId)
                .orElseThrow(() -> new RuntimeException("医生不存在"));
        return appointmentRepository.findByDoctorAndStatus(doctor, Appointment.Status.PENDING);
    }

    // 药品数量DTO
    public record MedicineQuantity(Long medicineId, Integer quantity) {}
}